<template>
  <div class="building-detail">
    <div class="page-header">
      <div class="header-left">
        <el-page-header @back="goBack" :content="buildingInfo.name || '楼宇详情'"></el-page-header>
      </div>
      <!-- <div class="header-right">
        <el-button type="primary" @click="openDialog">编辑信息</el-button>
      </div> -->
    </div>

    <el-card v-loading="loading" class="info-card">
      <div class="card-header">
        <h3>基本信息</h3>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">楼宇ID：</span>
            <span class="value">{{ buildingInfo.building_id }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">楼宇名称：</span>
            <span class="value">{{ buildingInfo.name }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">所属园区：</span>
            <span class="value">{{ buildingInfo.park ? buildingInfo.park.name : '-' }}</span>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">总楼层：</span>
            <span class="value">{{ buildingInfo.total_floors }} 层</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">建筑面积：</span>
            <span class="value">{{ buildingInfo.building_area }} ㎡</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">建成日期：</span>
            <span class="value">{{ buildingInfo.completion_date }}</span>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">楼宇类型：</span>
            <span class="value">{{ buildingInfo.building_type }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">结构类型：</span>
            <span class="value">{{ buildingInfo.structure_type || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">消防等级：</span>
            <span class="value">{{ buildingInfo.fire_rating || '-' }}</span>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ buildingInfo.created_at }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">更新时间：</span>
            <span class="value">{{ buildingInfo.updated_at }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="statistic-card">
      <div class="card-header">
        <h3>楼宇概况</h3>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="statistic-item">
            <div class="statistic-title">总房间数</div>
            <div class="statistic-value">{{ statistics.totalRooms }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="statistic-item">
            <div class="statistic-title">已租房间</div>
            <div class="statistic-value">{{ statistics.rentedRooms }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="statistic-item">
            <div class="statistic-title">空置房间</div>
            <div class="statistic-value">{{ statistics.vacantRooms }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="statistic-item">
            <div class="statistic-title">出租率</div>
            <div class="statistic-value">{{ statistics.occupancyRate }}%</div>
          </div>
        </el-col>
      </el-row>

      <div class="chart-container">
        <div id="rentChart" class="chart"></div>
      </div>
    </el-card>

    <el-card class="detail-card">
      <div class="card-header">
        <h3>楼层列表</h3>
      </div>
        <el-table
          :data="floorList"
          style="width: 100%;"
          border
          :header-cell-style="{ background: '#f8f9fa', color: '#333' }">
          <el-table-column
            prop="floorNumber"
            label="楼层"
            width="100"
            align="center">
            <template #default="scope">
              {{ scope.row.floorNumber }}层
            </template>
          </el-table-column>
          <el-table-column
            prop="area"
            label="面积(㎡)"
            width="120"
            align="center">
          </el-table-column>
          <el-table-column
            prop="roomCount"
            label="房间数"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="rentedCount"
            label="已租数"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="rentRate"
            label="出租率"
            width="100"
            align="center">
            <template #default="scope">
              {{ scope.row.rentRate }}%
            </template>
          </el-table-column>
          <el-table-column
            prop="usage"
            label="用途"
            min-width="180">
          </el-table-column>
          <el-table-column
            label="操作"
            width="120"
            align="center">
            <template #default="scope">
              <el-button @click="viewFloorDetail(scope.row)" type="text" size="small">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
    </el-card>
    
    <el-card class="detail-card">
      <div class="card-header">
        <h3>设备概览</h3>
      </div>
      <div v-if="deviceList && deviceList.length > 0" class="device-list-container">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(device, index) in deviceList" :key="index" class="device-col">
            <el-card shadow="hover" :body-style="{ padding: '15px' }">
              <div class="device-card-header">
                <span class="device-name">{{ device.name }}</span>
                <el-tag :type="getStatusTagType(device.status)" size="small">{{ device.status }}</el-tag>
              </div>
              <div class="device-card-body">
                <div><strong>类型:</strong> {{ device.type }}</div>
                <div><strong>位置:</strong> {{ device.location }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-empty v-else description="暂无设备信息"></el-empty>
    </el-card>

    <!-- 楼宇编辑对话框 -->
    <el-dialog title="编辑楼宇信息" v-model:visible="dialogVisible" width="600px">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入名称/编号"></el-input>
        </el-form-item>
        <el-form-item label="总楼层" prop="total_floors">
          <el-input-number v-model="editForm.total_floors" :min="1" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="建筑面积" prop="building_area">
          <el-input v-model="editForm.building_area" placeholder="请输入建筑面积">
            <template #append>㎡</template>
          </el-input>
        </el-form-item>
        <el-form-item label="建成日期" prop="completion_date">
          <el-date-picker
            v-model="editForm.completion_date"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="楼宇类型" prop="building_type">
          <el-select v-model="editForm.building_type" placeholder="请选择类型">
            <el-option label="办公楼" value="办公楼"></el-option>
            <el-option label="厂房" value="厂房"></el-option>
            <el-option label="研发楼" value="研发楼"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结构类型" prop="structure_type">
          <el-input v-model="editForm.structure_type" placeholder="请输入结构类型"></el-input>
        </el-form-item>
        <el-form-item label="消防等级" prop="fire_rating">
          <el-input v-model="editForm.fire_rating" placeholder="请输入消防等级"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBuildingDetail, getBuildingFloors, getBuildingDevices } from '@/api/assets.js'
// 引入 ECharts 主模块
import * as echarts from 'echarts/core';
// 引入饼图
import { PieChart } from 'echarts/charts';
// 引入提示框、图例等组件
import {
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
// 引入 Canvas 渲染器
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer
]);

export default {
  name: 'BuildingDetail',
  data() {
    return {
      loading: false,
      buildingId: '',
      buildingInfo: {
        building_id: '',
        park: {
          park_id: '',
          name: ''
        },
        name: '',
        total_floors: 0,
        building_area: '',
        completion_date: '',
        building_type: '',
        structure_type: '',
        fire_rating: '',
        created_at: '',
        updated_at: ''
      },
      statistics: {
        totalRooms: 0,
        rentedRooms: 0,
        vacantRooms: 0,
        occupancyRate: 0
      },
      floorList: [],
      deviceList: [],
      dialogVisible: false,
      editForm: {
        building_id: '',
        name: '',
        total_floors: 0,
        building_area: '',
        completion_date: '',
        building_type: '',
        structure_type: '',
        fire_rating: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        total_floors: [
          { required: true, message: '请输入总楼层', trigger: 'blur' }
        ],
        building_area: [
          { required: true, message: '请输入建筑面积', trigger: 'blur' }
        ],
        building_type: [
          { required: true, message: '请选择楼宇类型', trigger: 'change' }
        ],
        completion_date: [
          { required: true, message: '请选择建成日期', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.buildingId = this.$route.params.id
    this.fetchBuildingInfo()
    this.fetchFloorList()
    this.fetchDeviceList()
  },
  mounted() {
    // ECharts a needs a DOM element, so it must be initialized in mounted hook.
    // this.initChart()
  },
  methods: {
    // 获取楼宇信息
    async fetchBuildingInfo() {
      this.loading = true
      try {
        const response = await getBuildingDetail(this.buildingId)
        if (response.data.code === 200) {
          this.buildingInfo = response.data.data
        }
      } catch (error) {
        this.$message.error('获取楼宇详情失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 获取楼层列表
    async fetchFloorList() {
      try {
        const response = await getBuildingFloors(this.buildingId)
        if (response.data.code === 200) {
          this.floorList = response.data.data
          this.calculateStatistics()
          this.$nextTick(() => {
            this.initChart()
          })
        }
      } catch (error) {
        this.$message.error('获取楼层列表失败')
        console.error(error)
      }
    },
    // 获取设备列表
    async fetchDeviceList() {
      try {
        const response = await getBuildingDevices(this.buildingId)
        if (response.data.code === 200) {
          this.deviceList = response.data.data
        }
      } catch (error) {
        this.$message.error('获取设备列表失败')
        console.error(error)
      }
    },
    // 计算统计数据
    calculateStatistics() {
      let totalRooms = 0
      let rentedRooms = 0
      this.floorList.forEach(floor => {
        totalRooms += floor.roomCount
        rentedRooms += floor.rentedCount
      })

      this.statistics = {
        totalRooms,
        rentedRooms,
        vacantRooms: totalRooms - rentedRooms,
        occupancyRate: totalRooms > 0 ? ((rentedRooms / totalRooms) * 100).toFixed(1) : 0
      }
    },
    // 初始化图表
    initChart() {
      const chartDom = document.getElementById('rentChart');
      if (!chartDom) return;

      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '房源统计',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: this.statistics.rentedRooms, name: '已租房间' },
              { value: this.statistics.vacantRooms, name: '空置房间' },
            ]
          }
        ]
      };
      myChart.setOption(option);
    },
    // 返回上一页
    goBack() {
      this.$router.push('/admin/assets/BuildingList')
    },
    // 打开编辑对话框
    openDialog() {
      this.editForm = JSON.parse(JSON.stringify(this.buildingInfo))
      this.dialogVisible = true
    },
    // 提交表单
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 调用编辑接口
          console.log('编辑楼宇', this.editForm)
          this.$message.success('编辑成功')
          this.dialogVisible = false
          // 更新楼宇信息
          this.buildingInfo = { ...this.buildingInfo, ...this.editForm }
        } else {
          return false
        }
      })
    },
    // 查看楼层详情
    viewFloorDetail(row) {
      this.$router.push(`/admin/assets/FloorDetail/${row.id}`)
    },
    // 获取设备状态对应的标签类型
    getStatusTagType(status) {
      switch (status) {
        case '正常':
        case '在线':
          return 'success'
        case '离线':
          return 'info'
        case '故障':
        case '异常':
          return 'danger'
        default:
          return 'warning'
      }
    }
  }
}
</script>

<style scoped>
.building-detail {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.info-card, .statistic-card, .detail-card {
  margin-bottom: 20px;
}
.card-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}
.info-item {
  margin-bottom: 15px;
}
.label {
  color: #606266;
  font-weight: bold;
}
.value {
  margin-left: 5px;
}
.statistic-item {
  text-align: center;
  padding: 20px 0;
  background-color: #f8f8f8;
  border-radius: 4px;
}
.statistic-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
.chart-container {
  height: 300px;
  margin-top: 20px;
}
.chart {
  height: 100%;
  width: 100%;
}
.device-list-container {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}
.device-col {
  margin-bottom: 20px;
}
.device-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.device-name {
  font-weight: bold;
  font-size: 16px;
}
.device-card-body div {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}
.device-card-body div:last-child {
  margin-bottom: 0;
}
.detail-tabs {
  margin-top: 20px;
}
.tab-content {
  padding: 20px 0;
}
</style> 